<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Model\FriendGroup;
use App\Model\FriendGroupUser;
use App\Model\Group;
use App\Model\GroupUser;
use App\Model\MessageLog;
use App\Model\User;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;

class IMController extends AbstractController
{
    /**
     * 新用户要添加的好友.
     */
    protected array $friendIds = [1, 2];

    /**
     * 新用户要添加的群聊.
     */
    protected array $groupIds = [1, 2];

    public function init(): ResponseInterface
    {
        $identity = $this->request->input('identity');
        if (!$identity) {
            return $this->errJson('请先登录！');
        }

        $code = mt_rand(100000, 999999);
        $user = User::query()->firstOrCreate(['identity' => $identity], [
            'username' => '码屌' . $code,
            'sign' => '我的个性签名',
            'code' => $code,
            'avatar' => 'http://tva3.sinaimg.cn/crop.0.0.180.180.180/7f5f6861jw1e8qgp5bmzyj2050050aa8.jpg',
            'identity' => $identity,
        ]);

        //新用户默认添加好友和群聊
        if ($user->wasRecentlyCreated) {
            $friendGroup = FriendGroup::create(['user_id' => $user->id, 'group_name' => '我的好友']);
            foreach ($this->friendIds as $friendId) {
                if (User::query()->find($friendId)) {
                    FriendGroupUser::query()->create([
                        'user_id' => $friendId,
                        'friend_group_id' => $friendGroup->id,
                    ]);
                }
            }
            foreach ($this->groupIds as $groupId) {
                if (Group::query()->where('status', 1)->find($groupId)) {
                    GroupUser::query()->create([
                        'group_id' => $groupId,
                        'user_id' => $user->id,
                    ]);
                }
            }
        } else {
            $user->status = 'online';
            $user->save();
        }

        $res['mine'] = $user->only('username', 'id', 'status', 'sign', 'avatar');
        $res['friend'] = $user->friendGroups->map(function ($friendGroup) {
            $friend['groupname'] = $friendGroup->group_name;
            $friend['id'] = $friendGroup->id;
            $friend['list'] = $friendGroup->users->map(function ($user) {
                return $user->only('username', 'id', 'status', 'sign', 'avatar');
            });
            return $friend;
        });
        $res['group'] = $user->groups->map(function ($group) {
            return [
                'groupname' => $group->group_name,
                'id' => $group->id,
                'avatar' => $group->avatar,
            ];
        });
        return $this->sucJson($res);
    }

    /**
     * 获取群员.
     */
    public function members(): ResponseInterface
    {
        $id = $this->request->input('id');
        $group = Group::query()->find($id);
        if (!$group) {
            return $this->errJson('不存在的群聊！');
        }
        $data['list'] = $group->users->map(function ($user) {
            return [
                'username' => $user['username'],
                'id' => $user['id'],
                'avatar' => $user['avatar'],
                'sign' => $user['sign'],
            ];
        });
        return $this->sucJson($data);
    }

    /**
     * 上传文件.
     */
    public function uploadFile(): ResponseInterface
    {
        if (!$this->request->hasFile('file')) {
            return $this->errJson('上传文件不存在！');
        }
        $file = $this->request->file('file');
        if (!$file->isValid()) {
            return $this->errJson('上传文件无效！');
        }

        $user = Context::get('user');
        $ext = $file->getExtension();
        if (in_array(strtolower($ext), ['jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp'])
            && in_array(exif_imagetype($file->getPath() . '/' . $file->getFilename()), [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_BMP])) {
            $name = $user->id . '-' . uniqid() . '.' . $ext;
            $file->moveTo(BASE_PATH . '/public/uploads/image/' . $name);
            if ($file->isMoved()) {
                return $this->sucJson(['src' => '/uploads/image/' . $name]);
            }
            return $this->errJson('上传文件失败！');
        }
        $name = $user->id . '-' . uniqid() . '.' . $ext;
        $file->moveTo(BASE_PATH . '/public/uploads/file/' . $name);
        if ($file->isMoved()) {
            return $this->sucJson(['src' => '/uploads/file/' . $name, 'name' => $file->getClientFilename()]);
        }
        return $this->errJson('上传文件失败！');
    }

    /**
     * 修改签名.
     */
    public function sign(): ResponseInterface
    {
        $user = Context::get('user');
        $sign = $this->request->input('sign');
        $user->sign = $sign;
        $user->save();
        return $this->sucJson('修改签名成功！');
    }

    /**
     * 修改在线状态
     */
    public function online(): ResponseInterface
    {
        $user = Context::get('user');
        $sign = $this->request->input('online');
        if ($sign == 'hide') {
            $user->status = 'offline';
        } elseif ($sign == 'online') {
            $user->status = 'online';
        } else {
            return $this->errJson('参数错误！');
        }
        $user->save();
        return $this->sucJson('修改状态成功！');
    }


    /**
     * 聊天记录
     * @return ResponseInterface
     */
    public function chatLog()
    {
        $user = Context::get('user');
        $toId = $this->request->input('id');
        $type = $this->request->input('type');

        if ($type == 'friend') {
            $data = MessageLog::query()
                ->where('type', $type)
                ->where(function ($query) use ($user, $toId) {
                    $query->where(['send_id' => $user->id, 'to_id' => $toId])->orWhere(['to_id' => $user->id, 'send_id' => $toId]);
                })
                ->with('sendUser')
                ->orderBy('created_at', 'desc')
                ->get()->toArray();
        }else{
            $data = MessageLog::query()
                ->where('type', $type)
                ->where('to_id',$toId)
                ->with('sendUser')
                ->orderBy('created_at', 'desc')
                ->get()->toArray();
        }
        $res = [];
        foreach ($data as $v){
            $tmp['username'] = $v['send_user']['username'];
            $tmp['id'] = $v['send_user']['id'];
            $tmp['avatar'] = $v['send_user']['avatar'];
            $tmp['timestamp'] = strtotime((string)$v['created_at']) * 1000;
            $tmp['content'] = $v['content'];
            $res[] = $tmp;
        }
        return $this->sucJson($res);
    }


}
